<template>
  <teleport to="body">
    <div v-if="menuStore.isVisible" class="global-context-menu-container">
      <div 
        ref="menuEl"
        class="global-context-menu" 
        :style="menuStyle"
        @click.stop
      >
        <!-- 表格浏览器菜单 -->
        <template v-if="menuStore.menuType === 'tableBrowser'">
          <div 
            v-for="(item, index) in tableBrowserMenuItems" 
            :key="index"
            :class="['menu-item', { 'danger': item.danger, 'divider': item.isDivider }]"
            @click="handleItemClick(item)"
          >
            <template v-if="!item.isDivider">
              <Icon v-if="item.iconify" :icon="item.iconify" class="menu-icon" />
              <el-icon v-else-if="item.icon" class="menu-icon">
                <component :is="item.icon" />
              </el-icon>
              <span class="menu-label">{{ item.label }}</span>
            </template>
          </div>
        </template>
        
        <!-- 连接菜单 -->
        <template v-else-if="menuStore.menuType === 'connection'">
          <div 
            v-for="(item, index) in getConnectionMenuItems()" 
            :key="index"
            :class="['menu-item', { 'danger': item.danger, 'divider': item.isDivider }]"
            @click="handleItemClick(item)"
          >
            <template v-if="!item.isDivider">
              <Icon v-if="item.iconify" :icon="item.iconify" class="menu-icon" />
              <el-icon v-else-if="item.icon" class="menu-icon">
                <component :is="item.icon" />
              </el-icon>
              <span class="menu-label">{{ item.label }}</span>
            </template>
          </div>
        </template>
        
        <!-- 数据库菜单 -->
        <template v-else-if="menuStore.menuType === 'database'">
          <div 
            v-for="(item, index) in databaseMenuItems" 
            :key="index"
            :class="['menu-item', { 'danger': item.danger, 'divider': item.isDivider }]"
            @click="handleItemClick(item)"
          >
            <template v-if="!item.isDivider">
              <Icon v-if="item.iconify" :icon="item.iconify" class="menu-icon" />
              <el-icon v-else-if="item.icon" class="menu-icon">
                <component :is="item.icon" />
              </el-icon>
              <span class="menu-label">{{ item.label }}</span>
            </template>
          </div>
        </template>
        
        <!-- 表分类菜单 -->
        <template v-else-if="menuStore.menuType === 'category_tables'">
          <div 
            v-for="(item, index) in tablesCategoryMenuItems" 
            :key="index"
            :class="['menu-item', { 'danger': item.danger, 'divider': item.isDivider }]"
            @click="handleItemClick(item)"
          >
            <template v-if="!item.isDivider">
              <Icon v-if="item.iconify" :icon="item.iconify" class="menu-icon" />
              <el-icon v-else-if="item.icon" class="menu-icon">
                <component :is="item.icon" />
              </el-icon>
              <span class="menu-label">{{ item.label }}</span>
            </template>
          </div>
        </template>
        
        <!-- 其他分类菜单 -->
        <template v-else-if="menuStore.menuType.startsWith('category_')">
          <div 
            v-for="(item, index) in categoriesMenuItems" 
            :key="index"
            :class="['menu-item', { 'danger': item.danger, 'divider': item.isDivider }]"
            @click="handleItemClick(item)"
          >
            <template v-if="!item.isDivider">
              <Icon v-if="item.iconify" :icon="item.iconify" class="menu-icon" />
              <el-icon v-else-if="item.icon" class="menu-icon">
                <component :is="item.icon" />
              </el-icon>
              <span class="menu-label">{{ item.label }}</span>
            </template>
          </div>
        </template>
        
        <!-- 表菜单 -->
        <template v-else-if="menuStore.menuType === 'table'">
          <div 
            v-for="(item, index) in tableMenuItems" 
            :key="index"
            :class="['menu-item', { 'danger': item.danger, 'divider': item.isDivider }]"
            @click="handleItemClick(item)"
          >
            <template v-if="!item.isDivider">
              <Icon v-if="item.iconify" :icon="item.iconify" class="menu-icon" />
              <el-icon v-else-if="item.icon" class="menu-icon">
                <component :is="item.icon" />
              </el-icon>
              <span class="menu-label">{{ item.label }}</span>
            </template>
          </div>
        </template>
        
        <!-- 视图菜单 -->
        <template v-else-if="menuStore.menuType === 'view'">
          <div 
            v-for="(item, index) in viewMenuItems" 
            :key="index"
            :class="['menu-item', { 'danger': item.danger, 'divider': item.isDivider }]"
            @click="handleItemClick(item)"
          >
            <template v-if="!item.isDivider">
              <Icon v-if="item.iconify" :icon="item.iconify" class="menu-icon" />
              <el-icon v-else-if="item.icon" class="menu-icon">
                <component :is="item.icon" />
              </el-icon>
              <span class="menu-label">{{ item.label }}</span>
            </template>
          </div>
        </template>
        
        <!-- 查询菜单 -->
        <template v-else-if="menuStore.menuType === 'query'">
          <div 
            v-for="(item, index) in queryMenuItems" 
            :key="index"
            :class="['menu-item', { 'danger': item.danger, 'divider': item.isDivider }]"
            @click="handleItemClick(item)"
          >
            <template v-if="!item.isDivider">
              <Icon v-if="item.iconify" :icon="item.iconify" class="menu-icon" />
              <el-icon v-else-if="item.icon" class="menu-icon">
                <component :is="item.icon" />
              </el-icon>
              <span class="menu-label">{{ item.label }}</span>
            </template>
          </div>
        </template>
      </div>
    </div>
  </teleport>
</template>

<script setup>
import { computed, onMounted, onUnmounted, ref, nextTick, watch } from 'vue'
import { useMenuStore } from '@/stores'
import { View, Edit, Document, Refresh, Link, Close, Delete, Grid, Operation, EditPen, CopyDocument } from '@element-plus/icons-vue'
import { Icon } from '@iconify/vue'

// 初始化store
const menuStore = useMenuStore()

// 菜单元素引用
const menuEl = ref(null)

// 菜单实际尺寸
const menuSize = ref({ width: 180, height: 200 }) // 默认值

// 监听菜单可见性变化，在菜单显示后获取其实际尺寸
watch(() => menuStore.isVisible, async (isVisible) => {
  if (isVisible) {
    // 等待DOM更新
    await nextTick()
    // 获取菜单实际尺寸
    if (menuEl.value) {
      const { offsetWidth, offsetHeight } = menuEl.value
      menuSize.value = {
        width: offsetWidth,
        height: offsetHeight
      }
    }
  }
}, { immediate: true })

// 计算菜单样式
const menuStyle = computed(() => {
  const { x, y } = menuStore.menuPosition
  
  // 获取视口尺寸
  const viewportWidth = window.innerWidth
  const viewportHeight = window.innerHeight
  
  // 获取菜单尺寸
  const { width: menuWidth, height: menuHeight } = menuSize.value
  
  // 设置安全边距
  const safeMargin = 5
  
  let left = x
  let top = y
  
  // 水平方向溢出处理
  if (x + menuWidth + safeMargin > viewportWidth) {
    // 尝试在点击位置左侧显示
    left = x - menuWidth
    
    // 如果左侧也放不下，找个最合适的位置
    if (left < safeMargin) {
      left = Math.max(safeMargin, Math.min(x, viewportWidth - menuWidth - safeMargin))
    }
  }
  
  // 垂直方向溢出处理
  if (y + menuHeight + safeMargin > viewportHeight) {
    // 尝试在点击位置上方显示
    top = y - menuHeight
    
    // 如果上方也放不下，找个最合适的位置
    if (top < safeMargin) {
      top = Math.max(safeMargin, Math.min(y, viewportHeight - menuHeight - safeMargin))
    }
  }
  
  return {
    position: 'fixed',
    left: `${left}px`,
    top: `${top}px`,
    zIndex: 9999,
  }
})

// 表格浏览器菜单项
const tableBrowserMenuItems = [
  { command: 'browseData', label: '浏览数据', iconify: 'mdi:table-eye' },
  { command: 'designTable', label: '设计表', iconify: 'mdi:table-edit' },
  { command: 'newQuery', label: '新建查询', iconify: 'mdi:file-document-edit' },
  { isDivider: true },
  { command: 'refresh', label: '刷新', iconify: 'mdi:refresh' }
]

// 数据库菜单项
const databaseMenuItems = [
  { command: 'newQuery', label: '新建查询', iconify: 'mdi:file-document-edit' },
  { command: 'refresh', label: '刷新', iconify: 'mdi:refresh' }
]

// 表菜单项
const tableMenuItems = [
  { command: 'browseData', label: '浏览数据', iconify: 'mdi:table-eye' },
  { command: 'designTable', label: '设计表', iconify: 'mdi:table-edit' },
  { command: 'newQuery', label: '新建查询', iconify: 'mdi:file-document-edit' },
  { isDivider: true },
  { command: 'refresh', label: '刷新', iconify: 'mdi:refresh' },
  { command: 'truncateTable', label: '清空表', iconify: 'mdi:delete-sweep', danger: true },
  { command: 'deleteTable', label: '删除表', iconify: 'mdi:delete', danger: true },
  { isDivider: true },
  { command: 'renameTable', label: '修改表名', iconify: 'mdi:pencil' },
  { command: 'copyTableName', label: '复制表名', iconify: 'mdi:content-copy' },
  { isDivider: true },
  { command: 'importData', label: '导入数据', iconify: 'mdi:upload' }
]

// 视图菜单项
const viewMenuItems = [
  { command: 'browseData', label: '浏览数据', iconify: 'mdi:eye' },
  { command: 'newQuery', label: '新建查询', iconify: 'mdi:file-document-edit' },
]

// 表分类菜单项
const tablesCategoryMenuItems = [
  { command: 'viewAllTables', label: '查看全部表', iconify: 'mdi:table-multiple' },
  { command: 'refresh', label: '刷新', iconify: 'mdi:refresh' },
]

// 通用分类菜单项
const categoriesMenuItems = [
  { command: 'refresh', label: '刷新', iconify: 'mdi:refresh' },
]

// 查询菜单项
const queryMenuItems = [
  { command: 'openQuery', label: '打开查询', iconify: 'mdi:file-document-outline' },
]

// 获取连接菜单项
const getConnectionMenuItems = () => {
  const isConnected = menuStore.menuData?.connection?.isConnected || 
                       (menuStore.menuData?.isConnected) || 
                       false
  
  const connectionType = menuStore.menuData?.connection?.type || ''
  
  const items = []
  
  if (!isConnected) {
    items.push({ command: 'connect', label: '连接', iconify: 'mdi:database-connect' })
  } else {
    items.push({ command: 'disconnect', label: '断开连接', iconify: 'mdi:database-off' })
  }
  
  items.push({ command: 'newQuery', label: '新建查询', iconify: 'mdi:file-document-edit' })
  
  // SQLite 不支持创建数据库
  if (isConnected && connectionType !== 'SQLite') {
    items.push({ command: 'createDatabase', label: '创建数据库/模式', iconify: 'mdi:database-plus' })
  }
  
  items.push({ isDivider: true })
  items.push({ command: 'edit', label: '编辑连接', iconify: 'mdi:pencil' })
  items.push({ command: 'delete', label: '删除连接', iconify: 'mdi:delete', danger: true })
  
  return items
}

// 处理菜单项点击
const handleItemClick = (item) => {
  if (item.isDivider) return
  
  menuStore.handleCommand(item.command)
}

// 组件挂载和卸载
onMounted(() => {
  console.log('全局菜单组件已挂载')
})

onUnmounted(() => {
  if (menuStore.isVisible) {
    menuStore.closeMenu()
  }
})
</script>

<style scoped>
.global-context-menu-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 9998;
  pointer-events: none; /* 不捕获指针事件，让底层元素能接收到点击 */
}

.global-context-menu {
  min-width: 200px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(229, 231, 235, 0.5);
  border-radius: 12px;
  box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 
              0 10px 10px -5px rgba(0, 0, 0, 0.04),
              0 0 0 1px rgba(0, 0, 0, 0.05);
  pointer-events: auto; /* 菜单本身可以接收事件 */
  animation: menuFadeIn 0.2s cubic-bezier(0.16, 1, 0.3, 1);
  overflow: hidden;
}

@keyframes menuFadeIn {
  from { 
    opacity: 0; 
    transform: scale(0.95);
    filter: blur(4px);
  }
  to { 
    opacity: 1; 
    transform: scale(1);
    filter: blur(0);
  }
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 10px 14px;
  cursor: pointer;
  transition: all 0.15s ease;
  font-size: 14px;
  color: #374151;
  border-radius: 8px;
  margin: 2px 4px;
}

.menu-item:hover {
  background-color: rgba(243, 244, 246, 0.8);
  transform: translateX(2px);
}

.menu-item.danger {
  color: #dc2626;
}

.menu-item.danger:hover {
  background-color: rgba(254, 226, 226, 0.8);
}

.menu-item.divider {
  height: 1px;
  padding: 0;
  margin: 6px 8px;
  background-color: rgba(229, 231, 235, 0.5);
  transform: none !important;
}

.menu-icon {
  width: 18px;
  height: 18px;
  margin-right: 10px;
  font-size: 16px;
  flex-shrink: 0;
  color: #6366f1;
  opacity: 0.9;
  transition: transform 0.2s ease;
}

.menu-item:hover .menu-icon {
  transform: scale(1.1);
}

.menu-item.danger .menu-icon {
  color: #ef4444;
}

.menu-label {
  flex: 1;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 暗色模式支持 */
@media (prefers-color-scheme: dark) {
  .global-context-menu {
    background: rgba(31, 41, 55, 0.95);
    border-color: rgba(75, 85, 99, 0.5);
  }
  
  .menu-item {
    color: #e5e7eb;
  }
  
  .menu-item:hover {
    background-color: rgba(55, 65, 81, 0.8);
  }
  
  .menu-item.danger {
    color: #f87171;
  }
  
  .menu-item.danger:hover {
    background-color: rgba(127, 29, 29, 0.5);
  }
  
  .menu-item.divider {
    background-color: rgba(75, 85, 99, 0.5);
  }
  
  .menu-icon {
    color: #818cf8;
  }
  
  .menu-item.danger .menu-icon {
    color: #f87171;
  }
}
</style> 